package org.example.aienglishapp.service.progress;

import org.example.aienglishapp.entity.progress.UsersProgress;
import org.example.aienglishapp.mapper.progress.UsersProgressMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class UserProgressService {

    private final UsersProgressMapper usersProgressMapper;

    @Autowired
    public UserProgressService(UsersProgressMapper usersProgressMapper) {
        this.usersProgressMapper = usersProgressMapper;
    }

    public Optional<UsersProgress> getUserProgress(Long userId) {
        return usersProgressMapper.getUserProgress(userId);
    }

    @Transactional
    public UsersProgress createOrUpdateUserProgress(UsersProgress usersProgress) {
        Optional<UsersProgress> existing = usersProgressMapper.getUserProgress(usersProgress.getUserId());
        if (existing.isPresent()) {
            usersProgress.setId(existing.get().getId());
            usersProgressMapper.updateUserProgress(usersProgress);
        } else {
            usersProgressMapper.insertUserProgress(usersProgress);
        }
        return usersProgress;
    }
}